package com.tptj.demo.hg.export.operate.provider;

import com.fanruan.api.report.export.BaseAppExporter;
import com.fr.intelli.record.Focus;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.main.workbook.ResultWorkBook;
import com.fr.record.analyzer.EnableMetrics;
import com.fr.report.cell.CellElement;
import com.fr.report.report.ResultECReport;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Iterator;

/**
 * @author 秃破天际
 * @version 10.0
 * Created by 秃破天际 on 2021-04-07
 * 简单导出单元格内容的demo
 **/
@EnableMetrics
public class JsonExporter extends BaseAppExporter {
    @Override
    @Focus(id="com.tptj.demo.hg.export.operate.provider.v10",text = "export operate provider")
    public void export(OutputStream out, ResultWorkBook book ) throws Exception {
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));
        int sheet_count = book.getReportCount();
        JSONObject rt = JSONObject.create();
        JSONArray rt_sheet = JSONArray.create();
        rt.put("sheets",rt_sheet);
        for( int i=0; i<sheet_count; i++ ){
            ResultECReport sheet = (ResultECReport) book.getResultReport(i);
            rt_sheet.put( sheet2Json( sheet, book.getReportName(i), i ) );
        }
        writer.print( rt.toString() );
        writer.close();
    }
    @SuppressWarnings("unchecked")
    private JSONObject sheet2Json( ResultECReport sheet,String name,int idx ) throws Exception {
        JSONObject jo_sheet = JSONObject.create().put("name",name).put("idx",idx);
        JSONArray ja_cells = JSONArray.create();
        Iterator<CellElement> cells = sheet.cellIterator();
        while ( cells.hasNext() ){
            CellElement cell = cells.next();
            ja_cells.put( cell2Json(cell) );
        }
        return jo_sheet.put("cells",ja_cells);
    }

    private JSONObject cell2Json( CellElement cell ) throws Exception {
        //注：demo只处理简单的单元格值，对于单元格图表/文件等特殊值不做处理！
        JSONObject rt_cell = JSONObject.create()
                .put( "row", cell.getRow() )
                .put( "row_span", cell.getRowSpan() )
                .put( "col", cell.getColumn() )
                .put( "col_span", cell.getColumnSpan() )
                .put( "text", cell.getShowValue() )
                .put( "value", cell.getValue() );
        return rt_cell;
    }


}
